package com.zenika.zenbinding.client.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.user.client.ui.Widget;
import com.zenika.zenbinding.client.exception.DataMessage;
import com.zenika.zenbinding.client.feedback.DummyFeedbackManager;
import com.zenika.zenbinding.client.handler.Handler;
import com.zenika.zenbinding.client.renderer.Renderer;

public class CellModel {
  
  private int column;
  private List<CellModelListener> listenerList;
  private BusinessObject object;
  private Renderer renderer;
  private int row;
  private Handler tableHandler;
  
  public CellModel(int row, int column, BusinessObject object, Renderer renderer) {
    this.listenerList = new ArrayList<CellModelListener>();
    this.row = row;
    this.object = object;
    this.column = column;
    this.renderer = renderer;
  }
  
  public void addCellModelListener(CellModelListener listener) {
    this.listenerList.add(listener);
  }
  
  public void fireError(DataMessage message) {
    Iterator<CellModelListener> iter = this.listenerList.iterator();
    while ( iter.hasNext() ) {
      iter.next().onEnteringErrorState(this.row, this.column, this.tableHandler, message);
    }
  }
  
  public void fireErrorStop() {
    Iterator<CellModelListener> iter = this.listenerList.iterator();
    while ( iter.hasNext() ) {
      iter.next().onLeavingErrorState(this.row, this.column, this.tableHandler);
    }
  }
  
  /**
   * We request an handler in parameter to identify which handler had requested the view.
   * 
   * @param handler
   * @return The widget to display in the cell
   */
  public Widget getView(Handler handler) {
    this.tableHandler = handler;
    DummyFeedbackManager dummy = new DummyFeedbackManager(this);
    return this.renderer.render(this.object, dummy);
  }
  
  public void removeCellModelListener(CellModelListener listener) {
    this.listenerList.remove(listener);
  }
}
